package com.example.controller;


import com.example.dao.DocumentVideoCrudRepository;
import com.example.dao.UserCrudRepository;
import com.example.pojo.*;
import com.example.tools.JwtUtils;
import com.example.tools.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/documentVideo")
@Slf4j
public class DocumentVideoController {
    @Autowired
    private DocumentVideoCrudRepository documentVideoCrudRepository;
    @Autowired
    private UserCrudRepository userCrudRepository;

    @PostMapping("/addDocumentVideo")
    @Transactional
    public Result add(@RequestBody List<DocumentVideo> documentVideos, @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        System.out.println(documentVideos);
        for (DocumentVideo documentVideo : documentVideos) {
            documentVideo.setAgencyId(user.getAgencyId());
            if (user.getRole().equals("超级管理员")) {
                documentVideo.setStatus("已发布");
            } else if (user.getRole().equals("机构管理员")) {
                documentVideo.setStatus("未审核");
            }
            documentVideoCrudRepository.save(documentVideo);
        }
        return Result.success();
    }

    @DeleteMapping("/deleteDocumentVideo")
    public Result delete(@RequestBody List<Integer> ids, @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        String result = "";
        for (Integer testQuestionId : ids) {
            DocumentVideo testQuestion = documentVideoCrudRepository.findById(testQuestionId).get();
            if (testQuestion.getAgencyId() == user.getAgencyId()) {
                documentVideoCrudRepository.deleteById(testQuestionId);
            } else {
                result = result + testQuestionId + " ";
            }
        }
        if (result.equals("")) {
            return Result.success("删除成功");
        }
        return Result.error("编号为:" + result + "的试题为共享视频,无权删除");
    }

    @PostMapping("/updateDocumentVideo")
    public Result update(@RequestBody DocumentVideo documentVideo, @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        //机构管理员没有权限操作超级管理员上传的文件
        if (user.getRole().equals("机构管理员") && documentVideo.getAgencyId() == 0) {
            return Result.error("没有权限");
        }
        DocumentVideo save = documentVideoCrudRepository.save(documentVideo);
        return Result.success(save);
    }

    @PostMapping("/getAllDocumentVideo")
    public Result getAllDocumentVideo(@RequestBody DocumentVideo documentVideo,
                                      @RequestParam(defaultValue = "1") Integer page,
                                      @RequestParam(defaultValue = "10") Integer pageSize,
                                      @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();

        log.info("documentVideo:{}", documentVideo);
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.Direction.ASC, "id");

        Page<DocumentVideo> coursePage = documentVideoCrudRepository.findAll(new Specification<DocumentVideo>() {
            @Override
            public Predicate toPredicate(Root<DocumentVideo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //获取条件对象
                Predicate predicate = cb.conjunction();
                //判断用户对象
                if (documentVideo != null) {
                    // 根据 student 的属性添加查询条件
                    if (documentVideo.getName() != null) {
                        predicate.getExpressions().add(cb.like(root.get("name"), "%" + documentVideo.getName() + "%"));
                    }
                    if (documentVideo.getId() != null) {
                        predicate.getExpressions().add(cb.equal(root.get("id"), documentVideo.getId()));
                    }
                    if (documentVideo.getType() != null) {
                        predicate.getExpressions().add(cb.equal(root.get("type"), documentVideo.getType()));
                    }
                    if (documentVideo.getStatus() != null) {
                        predicate.getExpressions().add(cb.equal(root.get("status"), documentVideo.getStatus()));
                    }
                    if (user.getAgencyId() != null) {
                        //查自己的视频库以及超级管理员发的共享库
                        predicate.getExpressions().add(cb.or(
                                cb.equal(root.get("agencyId"), user.getAgencyId()),
                                cb.equal(root.get("agencyId"), 0)
                        ));
                    }
                    if(user.getRole().equals("学员")){
                        predicate.getExpressions().add(cb.equal(root.get("status"), "已发布") );
                    }
                }
                return predicate;
            }
        }, pageable);
        List<DocumentVideo> DocumentVideos = coursePage.getContent();
        long elements = coursePage.getTotalElements();
        return Result.success(new PageBean(elements, DocumentVideos));
    }

    @GetMapping("/getDocumentVideoList")
    public Result getDocumentVideoList() {
        Iterable<DocumentVideo> all = documentVideoCrudRepository.findAll();
        List<DocumentVideo> DocumentVideoList = new ArrayList<>();
        for (DocumentVideo documentVideo : all) {
            DocumentVideoList.add(documentVideo);
        }
        return Result.success(DocumentVideoList);
    }

    @GetMapping("/getReviewDocumentVideoList")
    public Result getReviewDocumentVideoList(@RequestParam(defaultValue = "0") Integer searchChoose,//查询已审核（未发布）和未审核，1已审核，0审核
                                             @RequestParam(defaultValue = "1") Integer page,
                                             @RequestParam(defaultValue = "10") Integer pageSize,
                                             @RequestHeader("token") String token) {
        Integer id = JwtUtils.parseJWT(token).get("id", Integer.class);
        User user = userCrudRepository.findById(id).get();
        log.info("user:{}",user);
        Pageable pageable = PageRequest.of(page - 1, pageSize);
        if (searchChoose == 1) {
            //未发布
            Page<DocumentVideo> documentVideo = documentVideoCrudRepository
                    .getDocumentVideosByStatusAndAgencyId("未发布", user.getAgencyId(), pageable);
            List<DocumentVideo> documentVideos = documentVideo.getContent(); // 当前页的数据
            long totalElements = documentVideo.getTotalElements(); // 总记录数
            return Result.success(new PageBean(totalElements, documentVideos));
        } else {
            //未审核
            Page<DocumentVideo> documentVideo = documentVideoCrudRepository
                    .getDocumentVideosByStatusAndAgencyId("未审核", user.getAgencyId(), pageable);
            List<DocumentVideo> documentVideos = documentVideo.getContent(); // 当前页的数据
            long totalElements = documentVideo.getTotalElements(); // 总记录数
            return Result.success(new PageBean(totalElements, documentVideos));
        }
    }











}
